package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.IApCommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApCommentServiceImpl implements IApCommentService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = new ApComment();
//        apComment.setId(); //mongo可以自动赋值
        if(user.getUserId()==0){ //以游客身份评论
            apComment.setUserId(user.getUserId());
            apComment.setUserName("游客");
            apComment.setImage(null);
        }else{
            ResponseResult<ApUser> responseResult = userFeign.getById(user.getUserId());
            ApUser apUser = responseResult.getData();
            apComment.setUserId(user.getUserId());
            apComment.setUserName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }

        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setRepay(0);
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult loadComment(CommentDto dto) {

        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        1、根据文章id查询
//        2、根据评论时间排序
//        3、分页时条件是 评论时间<minTime

        if(dto.getSize()==null){
            dto.setSize(10);
        }
        Query query = new Query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(dto.getSize());

        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);

        List<ApCommentVo> commentVoList = new ArrayList<>();
        for (ApComment apComment : commentList) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment,apCommentVo);
//            都需要从APCommentLike表中查询当前登录人对这个评论是否点赞
            // TODO  当前登录人是否对这个评论点赞 稍后再做
//        redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");

            if (redisTemplate.hasKey("comment_like_"+user.getUserId()+"_"+apComment.getId())) {
                apCommentVo.setOperation(0); // 0:当前登录人已点赞  1、未点赞
            }else{
                apCommentVo.setOperation(1); // 0:当前登录人已点赞  1、未点赞
            }

            commentVoList.add(apCommentVo);
        }

        return ResponseResult.okResult(commentVoList);
    }

    @Override
    public ResponseResult commentLike(CommentLikeDto dto) {
        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

//        dto.getOperation()==0 点赞
//        dto.getOperation()==1 取消点赞
//        点赞还是取消点赞

        if(dto.getOperation()==0){
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation()); //  0 点赞 1 取消点赞
            mongoTemplate.save(apCommentLike);

//            还需要修改当前评论的点赞数 如果是sql：update ap_comment set likes = likes-1 where id=??

            Query query  = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",1);
            mongoTemplate.updateFirst(query,update,ApComment.class);

//            记录到Redis中 ：记录当前登录人是否对这个评论点赞
//            key要体现出 谁对哪个评论点赞
            redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");
        }else{  //取消点赞

//            把当前用户点赞的数据删除 delete from ap_comment_like where userId=?? and comment_id=??
            mongoTemplate.remove(new Query(Criteria.where("userId").is(user.getUserId()).and("commentId").is(dto.getCommentId())),ApCommentLike.class);

            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation()); //  0 点赞 1 取消点赞
            mongoTemplate.save(apCommentLike);

            Query query  = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateFirst(query,update,ApComment.class);

            //取消点赞 删除Redis中标记
            redisTemplate.delete("comment_like_"+user.getUserId()+"_"+dto.getCommentId());
        }

        return ResponseResult.okResult();
    }
}
